<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="50%"
    top="60px"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      :label-width="$i18n.locale === 'en-US' ? '100px' : '100px'"
    >
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="项目名称" prop="title">
            <el-input v-model="dataForm.title"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="dataForm.phone"></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12" style="color: #ddd">
                <el-form-item label="工作地点" prop="address">
                    <el-input v-model="dataForm.address"> </el-input>
                </el-form-item>
            </el-col> -->
        <el-col :span="12">
          <el-form-item label="工作时间" prop="times">
            <el-date-picker
              v-model="dataForm.times"
              type="daterange"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <p class="pdl60">
            <span class="tip">*</span> 缩略图<span
              >(支持png、jpg，建议尺寸288*288px，最多1张)</span
            >
          </p>
        </el-col>
        <el-col :span="12">
          <el-form-item label="" prop="pic">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="
                (res, file, fileList) => handleAvatarSuccess(res, file, 'pic')
              "
              :before-upload="(file) => beforeUploadHandle(file, 'pic')"
            >
              <img v-if="dataForm.pic" :src="dataForm.pic" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容" prop="content">
            <editor-vue
              style="margin-top: -30px"
              :content="dataForm.content"
              @EditorChange="getEditor"
              ref="infoIntroduceRef"
            ></editor-vue>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
    <!-- 裁剪框 -->
    <cropper-dlg
      v-if="showCropper"
      :dialogVisible.sync="showCropper"
      :img-file="currentFile"
      ref="vueCropper"
      @upload="cropperUpload"
    ></cropper-dlg>
  </el-dialog>
</template>

<script>
import Cookies from "js-cookie";
import debounce from "lodash/debounce";
import editorVue from "@/components/editor";
export default {
  data() {
    return {
      visible: false,
      url: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      dataForm: {
        id: "",
        content: "",
        title: "",
        phone: "",
        address: "",
        endTime: "",
        startTime: "",
        pic: "",
        times: [],
      },
      tempPhone: "",
      times: "",
      currentFile: "",
      cropperIndex: null,
      showCropper: false, //裁剪弹框
      isCropper: true, //上传之前是否显示裁剪
    };
  },
  components: {
    editorVue,
  },
  watch: {
    "dataForm.times": {
      handler(newval, oldval) {
        this.dataForm.startTime = newval[0];
        this.dataForm.endTime = newval[1];
      },
    },
  },
  computed: {
    dataRule() {
      return {
        title: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        content: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        startTime: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        times: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        pic: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  methods: {
    // 上传之前
    beforeUploadHandle(file, name) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error(
          this.$t("upload.tip", {
            format: "jpg、png、gif",
          })
        );
        return false;
      }
      if (this.isCropper) {
        //显示裁剪
        this.currentFile = file;
        this.cropperIndex = name;
        this.showCropper = true;
        this.$nextTick(() => {
          this.$refs.vueCropper.init();
        });
        return false;
      }
    },
    cropperUpload(data) {
      this.showCropper = false;
      if (data != "close") {
        //裁剪成功后获取的图片
        this.$http.post("/oss/file/aliyunUpload", data).then((res) => {
          if (res.data.code == 0) {
            this.handleAvatarSuccess(res.data, "", this.cropperIndex);
          }
        });
      }
    },
    handleAvatarSuccess(res, file, key) {
      this.dataForm[key] = res.data.url;
      // this.$refs["dataForm"].validateField(key);
    },
    // 上传成功
    successHandle1(res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.dataForm.pic = res.data.url;
    },
    getEditor(val) {
      this.dataForm.content = val;
    },
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.dataForm.times = [];
        this.$refs["dataForm"].resetFields();

        if (this.dataForm.id) {
          this.getInfo();
        } else {
          this.$nextTick(() => {
            this.$refs.infoIntroduceRef.init();
          });
        }
      });
    },
    //获取信息
    getInfo() {
      this.$http
        .get("/scenic/commvolunteer/" + this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          this.dataForm.times = [
            this.dataForm.startTime,
            this.dataForm.endTime,
          ];
          this.tempPhone = this.dataForm.phone;
          this.$nextTick(() => {
            this.$refs.infoIntroduceRef.init();
          });
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          this.dataForm.workTime = this.startTime + "-" + this.endTime;
          //加密
          let newDataForm = Object.assign({}, this.dataForm);
          if (newDataForm.phone && this.tempPhone != newDataForm.phone) {
            //编辑了
            newDataForm.phone = this.$CryptoJS.encrypt(newDataForm.phone);
          } else {
            newDataForm.phone = null;
          }
          this.$http[!newDataForm.id ? "post" : "put"](
            "/scenic/commvolunteer",
            newDataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      {
        leading: true,
        trailing: false,
      }
    ),
  },
};
</script>

<style lang="scss" scoped>
.pdl60 {
  padding-left: 40px;

  .tip {
    color: #f56c6c;
  }
}

.aui-content {
  .ql-container {
    height: auto !important;
  }

  .zyfw .ql-container.ql-snow {
    height: 300px !important;
  }
}
</style>
